
$(function () {
    let buttonGroup = [
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        // {
        //     id: 'btn_grid_columns',
        //     size: 'small',
        //     text: '列',
        //     iconCls: 'icon-text_columns',
        //     plain: true,
        //     onClick: btn_open_column_list
        // },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    // grid_1();
    // grid_2();

    // setTimeout(
    //     btn_search()
    // ,1000);
})

function onSelect(title, index) {
    switch (index) {
        case 0:
            let initGridTotalItem = $('#v_ysk_grid').data('kendoGrid');
            if (initGridTotalItem == undefined){
                grid_1();
                setTimeout(
                    btn_search()
                ,1000);
            }
            break;
        case 1:
            let grid = $('#v_yfk_grid').data('kendoGrid');
            if (grid == undefined){
                grid_2();
                setTimeout(
                    btn_search()
                ,1000);
            }
            break;
    }

}

function grid_1() {
    let SUFFIX = "_ysk";
    let client = new kendo.data.DataSource({data: []});
    let pay_type = new kendo.data.DataSource({data: []});
    let remark = new kendo.data.DataSource({data: []});

    let dataSource = new kendo.data.DataSource({
        schema: {
            model: {
                id: 'id',
                fields: {
                    money: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "money", aggregate: "sum"},
        ],
        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            client.data(unique(data, 'client'));
            pay_type.data(unique(data, 'pay_type'));
            remark.data(unique(data, 'remark'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},

        {
            field: "bill_date",
            title: '日期',
            width: 95,
            filterable: false, //{multi: true, search: true,dataSource: bill_date},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "client",
            title: '客户',
            width: 95,
            filterable: {multi: true, search: true,dataSource: client},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "pay_type",
            title: '收款类型',
            width: 95,
            filterable: {multi: true, search: true,dataSource: pay_type},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'money',
            title: '金额',
            width: 70,
            template: item => {
                return item.money ? parseFloat(item.money).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "remark",
            title: '备注',
            width: 200,
            filterable: {multi: true, search: true,dataSource: remark},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'memo',
            title: ' ',
            width: 200,
            filterable:false
        },
    ];
    let grid = $(`#v_ysk_grid`).kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columns:columns,
        columnMenu: false,
        excel: {
            fileName: "已收款.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });

            changeBackgroundColor();
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_ysk_grid').data('kendoGrid');
    // loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    $('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_ysk_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        // let id = dataItem.mainId;
    });
}

function grid_2() {
    let SUFFIX = "_yfk";
    let client = new kendo.data.DataSource({data: []});
    let pay_type = new kendo.data.DataSource({data: []});
    let remark = new kendo.data.DataSource({data: []});

    let dataSource = new kendo.data.DataSource({
        schema: {
            model: {
                id: 'id',
                fields: {
                    money: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "money", aggregate: "sum"},
        ],
        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            client.data(unique(data, 'client'));
            pay_type.data(unique(data, 'pay_type'));
            remark.data(unique(data, 'remark'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},

        {
            field: "bill_date",
            title: '日期',
            width: 95,
            filterable: false, //{multi: true, search: true,dataSource: bill_date},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "client",
            title: '加工商',
            width: 95,
            filterable: {multi: true, search: true,dataSource: client},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "pay_type",
            title: '付款类型',
            width: 95,
            filterable: {multi: true, search: true,dataSource: pay_type},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'money',
            title: '金额',
            width: 70,
            template: item => {
                return item.money ? parseFloat(item.money).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "remark",
            title: '备注',
            width: 200,
            filterable: {multi: true, search: true,dataSource: remark},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'memo',
            title: ' ',
            width: 200,
            filterable:false
        },
    ];
    let grid = $(`#v_yfk_grid`).kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columns:columns,
        columnMenu: false,
        excel: {
            fileName: "已付款.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });

            changeBackgroundColor();
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_yfk_grid').data('kendoGrid');
    // loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    $('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_yfk_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        // let id = dataItem.mainId;
    });
}


function btn_cancel_filter() {
    $('#v_sum_grid').data('kendoGrid').dataSource.filter({});
}

function btn_search() {
    // if (!flag) flag = 1;
    // $('#v_sum_grid').data('kendoGrid').dataSource.read({
    //     orderNo: $('#orderNo').combobox('getValue')
    // })
    let kGrid,start,end;
    switch (getSelectedIndex()) {
        case 0:
            kGrid= $('#v_ysk_grid').data('kendoGrid');
            start= $('#start').datebox('getValue');
            end= $('#end').datebox('getValue');
            $.messager.progress();
            $.ajax({
                url: 'dev/callProc',
                contentType: 'application/json',
                data: JSON.stringify(["usp_ysk_yfk",start,end,1,0]),
                type: 'post',
                dataType: 'json',
                success: function (cdata) {
                    // console.log(cdata)
                    kGrid.dataSource.data(cdata.data);
                },
                complete:function(){
                    $.messager.progress('close');
                }
            })
            break;
        case 1:
            kGrid= $('#v_yfk_grid').data('kendoGrid');
            start= $('#start').datebox('getValue');
            end= $('#end').datebox('getValue');
            $.messager.progress();
            $.ajax({
                url: 'dev/callProc',
                contentType: 'application/json',
                data: JSON.stringify(["usp_ysk_yfk",start,end,2,0]),
                type: 'post',
                dataType: 'json',
                success: function (cdata) {
                    // console.log(cdata)
                    kGrid.dataSource.data(cdata.data);
                },
                complete:function(){
                    $.messager.progress('close');
                }
            })
            break;

    }

}
//获取当前选中标签页索引
function getSelectedIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

function btn_open_column_list() {
    let kendoGridID = '#v_sum_grid';
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列'" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

//  打印
function btn_print() {
    let start = $('#start').datebox('getValue');
    let end = $('#end').datebox('getValue');
    let storageId = $('#storageId').combobox('getValue');
    if (!start || !end || !storageId) {
        $.messager.alert('提示', '请选择日期和仓库', 'warning');
        return;
    }
    window.parent.FR.doURLPDFPrint({
        url: $(window.parent.document.body).data('report_url'),
        isPopUp: false,
        data: {
            reportlets: [{
                reportlet: '材料收发存汇总.cpt',
                start: start,
                end: end,
                storageId: storageId
            }]
        }
    });
}

function btn_export_excel() {
    $('#v_sum_grid').data('kendoGrid').saveAsExcel();
}

function btn_close() {
    window.parent.closeTab();
}

// 行变色
function changeBackgroundColor(){
    let kGrid = $('#v_sum_grid').data('kendoGrid');
    // let gridRows = kGrid.tbody.find("tr");
    //
    // for(let i=0;i<gridRows.length;i++){
    //     const rowData = kGrid.dataItem(gridRows[i]);
    //     const mainState = rowData.mainState;
    //
    //     if( mainState == 2){
    //         // $(gridRows[i]).css("background-color", "blue"); // 修改背景颜色
    //         $(gridRows[i]).css("color", "blue"); // 修改颜色
    //     }
    //     // if( main_state == 0){
    //     //     // $(gridRows[i]).css("background-color", "blue"); // 修改背景颜色
    //     //     $(gridRows[i]).css("color", "red"); // 修改颜色
    //     // }
    // }

}